package com.weiiew.backend.config;

import com.weiiew.backend.utils.ScriptManager;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.File;
import java.io.IOException;
import java.nio.file.Path;

/**
 * @Description 脚本管理的配置类用于加载默认脚本存储位置
 * @Author 魏锴
 * @Date 2025/4/29
 */

@Configuration
public class ScriptManagerConfig {

    @Bean
    public ScriptManager scriptManager() throws IOException {
        // 构建脚本存储路径
        Path scriptPath = getJarParentPath().resolve("script");
        return new ScriptManager(scriptPath);
    }

    private Path getJarParentPath() {
        ApplicationHome home = new ApplicationHome(getClass());
        Path basePath = home.getDir().toPath();
        File source = home.getSource();
        boolean isJar = source != null && source.isFile() && source.getName().endsWith(".jar");
        return isJar
                ? basePath                            // JAR模式：jar所在目录/script
                : basePath.resolve("target");   // 开发模式：项目根目录/target/script
    }
}